package org.piax.rospubsub.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;

import org.piax.rospubsub.ADBBridge;
import org.piax.rospubsub.ADBBridgeMessage;
import org.piax.rospubsub.ServerADBBridge;
import org.piax.rospubsub.ADBBridge.ADBBridgeCallback;
import org.piax.rospubsub.ServerADBBridge.AcceptCallback;

/**
 * Android 側の Mock クラス。動作テスト用。
 * 
 * Android上で動くDTN adaptorの代わりに動かす。
 * Proxy からのメッセージを受けると、そのまま Proxy 側に送り返す。
 */
public class MockAndroid {
    public static void main(String[] args) {
        int listen_port = 8000;

        try {
            ServerADBBridge sbridge = new ServerADBBridge(new InetSocketAddress(listen_port), 
                    new AcceptCallback() {
                        @Override
                        public void onAccept(ADBBridge bridge) {
                            System.out.println("onAccept : " + bridge);
                        }
                    },
                    new ADBBridgeCallback() {
                        @Override
                        public void callback(ADBBridge bridge,
                                ADBBridgeMessage msg) {
                            System.out.println("callbacked : " + bridge);
                            System.out.println(" recv & send back : " + msg);
                            try {
                                bridge.send(msg);   // 投げ返す
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }, 8*1024);
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            // 終了指示待ちループ
            System.out.println("Start a shell. To escape this, enter 'bye'.");
            while (true) {
                try {
                    System.out.print("Input Command >");

                    String input = reader.readLine();
                    if (input == null) {
                        Thread.sleep(500);
                        continue;
                    }
                    String[] cmds = input.split("\\s+");

                    if (cmds.length == 0 || "".equals(cmds[0])) {
                        continue;
                    }
                    if (cmds[0].equals("bye")) {
                        break;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }
            }
            sbridge.close();
            System.out.println("Exit shell.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
